<template>
  <div v-loading="listLoading" style="min-height: 300px;">
    <u-table
      v-if="list.items.length > 0"
      ref="dayAccountTableRef"
      :data="list.items"
      :row-class-name="tableRowClassName"
      :height="tableHeight"
      :row-height="rowHeight()"
      :border="true"
      beautify-table
      header-drag-style
      use-virtual
      element-loading-text="加载中..."
      header-cell-class-name="order-data-header-cell"
      class="fb-table"
      empty-text="暂无数据"
      fit
      hightlight-current-row
      @select="selectTable"
      @select-all="selectTable"
      @sort-change="sortMethod">
      <u-table-column
        align="center"
        fixed="left"
        type="selection"
        width="50"/>
      <template v-for="(settingItem, index) in financeListSetting">
        <u-table-column
          v-if="(settingItem.fieldName !== 'orderSn' && settingItem.isShow) || (settingItem.fieldName === 'orderSn' && isIntelligent)"
          :key="index"
          v-bind="financeProps[settingItem.fieldName]">
          <template slot-scope="scope">
            <!-- 到账日期 -->
            <template v-if="settingItem.fieldName === 'arrivalTime'">
              <div>{{ scope.row.arrivalTime | standardFormat('YYYY/MM/DD') }}</div>
            </template>
            <!-- 交易单号 -->
            <template v-else-if="settingItem.fieldName === 'transactionNumber'">
              <ToolTip
                v-if="scope.row.transactionNumber"
                :content="scope.row.transactionNumber"
                :is-can-click="Boolean(intelligentRowCanClick(scope.row))"
                @handelClick="btnCheck(scope)" />
            </template>
            <!-- 收入金额 -->
            <template v-else-if="settingItem.fieldName === 'incomeAmount'">
              <PriceColumn :real-val="scope.row.incomeAmount" :price="scope.row.incomeAmount / 100" />
            </template>
            <!-- 可核销金额 -->
            <template v-else-if="settingItem.fieldName === 'unWriteOffAmount'">
              <PriceColumn :real-val="scope.row.unWriteOffAmount" :price="scope.row.unWriteOffAmount / 100" />
            </template>
            <!-- 付款人名称-->
            <template v-else-if="settingItem.fieldName === 'payName'">
              <ToolTip :content="scope.row.payName" />
            </template>
            <!-- 付款账号 -->
            <template v-else-if="settingItem.fieldName === 'payNumber'">
              <SecretText :log-text="`财务流水${scope.row.flowNumber}的付款账号`" :origin-text="scope.row.payNumber" />
            </template>
            <!-- 付款方式 -->
            <template v-else-if="settingItem.fieldName === 'clientType'">
              <ToolTip :content="getPayWay(scope.row)" />
            </template>
            <!-- 核销状态 -->
            <template v-else-if="settingItem.fieldName === 'verificationColor'">
              <div class="flex">
                <span :style="{backgroundColor: scope.row.verificationColor}" class="dot"/>
                <span>{{ scope.row.verificationState | setVerificationState }}</span>
              </div>
            </template>
            <!-- 封账状态 -->
            <template v-else-if="settingItem.fieldName === 'sealingState'">
              <div class="flex">
                <span :style="scope.row.sealingState === 1?{backgroundColor: '#31CC9C'}:{backgroundColor: '#FD8546'}" class="dot"/>
                <span>{{ scope.row.sealingState | setSealBillType }}</span>
              </div>
            </template>
            <!-- 备注  -->
            <template v-else-if="settingItem.fieldName === 'remark'">
              <div class="flex-center">
                <el-tooltip
                  v-if="scope.row.remark"
                  class="item"
                  placement="top">
                  <div slot="content" class="max-width-200">{{ scope.row.remark }}</div>
                  <div class="ellipsisOne">{{ scope.row.remark }}</div>
                </el-tooltip>
                <div v-else class="remarks">--</div>
                <i
                  v-if="(scope.row.verificationState === 0 && scope.row.sealingState === 0)"
                  class="el-icon-edit-outline"
                  style="margin-left:5px;font-size:16px;color: #406eff;cursor:pointer;"
                  @click="editRemark(scope.row)"/>
              </div>
            </template>
            <!-- 类型 -->
            <template v-else-if="settingItem.fieldName === 'flowType'">
              {{ scope.row.flowType | flowType }}
            </template>
            <!-- 订单编号 -->
            <template v-else-if="settingItem.fieldName === 'orderSn'">
              <ToolTip
                v-if="scope.row.orderSn && scope.row.orderId"
                :content="scope.row.orderSn"
                is-can-click
                @handelClick="toOrderDetail(scope.row)" />
              <div v-else>{{ scope.row.orderSn || '--' }}</div>
            </template>
            <!-- 流水单号 -->
            <template v-else-if="settingItem.fieldName === 'flowNumber'">
              {{ scope.row.flowNumber }}
            </template>
            <!-- 无需核销金额 -->
            <template v-else-if="settingItem.fieldName === 'noWriteOffAmount'">
              <PriceColumn :real-val="scope.row.noWriteOffAmount" :price="scope.row.noWriteOffAmount / 100" />
            </template>
            <!-- 关联发票金额 -->
            <template v-else-if="settingItem.fieldName === 'relatedInvoiceAmount'">
              <PriceColumn :real-val="scope.row.relatedInvoiceAmount" :price="scope.row.relatedInvoiceAmount / 100" />
            </template>
            <!-- 所属部门 -->
            <template v-else-if="settingItem.fieldName === 'departmentName'">
              <ToolTip :content="scope.row.departmentName" />
            </template>
            <!-- 封账月份 -->
            <template v-else-if="settingItem.fieldName === 'sealMonth'">
              {{ scope.row.sealMonth || '--' }}
            </template>
            <!-- 创建人 -->
            <template v-else-if="settingItem.fieldName === 'createName'">
              <CheckUserInfo v-if="scope.row.createName" :label="scope.row.createName" :user-id="scope.row.creatorId" />
              <div v-else>--</div>
            </template>
            <!-- 创建时间 -->
            <template v-else-if="settingItem.fieldName === 'createTime'">
              {{ scope.row.createTime | standardFormat('YYYY/MM/DD HH:mm') }}
            </template>
          </template>
        </u-table-column>
      </template>
      <u-table-column v-if="showOperate" :width="operateWidth" fixed="right" align="left" label="操作">
        <template slot-scope="scope">
          <div v-if="!showMobilePage" style="display:flex">
            <div v-if="intelligentRowCanClick(scope.row)" class="button-text" @click="btnCheck(scope)">查看</div>
            <div v-if="isIntelligent && scope.row.canOperate" class="button-text ml10 bl" @click="btnVerificate(scope)">核销</div>
            <el-dropdown v-if="!isIntelligent" trigger="click">
              <div class="el-dropdown-link">
                <div class="button-text">更多<i class="el-icon-arrow-down"/></div>
              </div>
              <el-dropdown-menu slot="dropdown" class="dropdown-wrap">
                <el-dropdown-item v-if="hasRouteAuth('crm:finance:edit')" :disabled="!(scope.row.verificationState === 0 && scope.row.sealingState === 0)" @click.native="btnEdit(scope)">
                  <div>编辑</div>
                </el-dropdown-item>
                <el-dropdown-item @click.native="btnVerificate(scope)">
                  <div>核销</div>
                </el-dropdown-item>
                <el-dropdown-item v-if="hasRouteAuth('crm:finance:delete')" :disabled="!(scope.row.verificationState === 0 && scope.row.sealingState === 0)" @click.native="btnDel(scope)">
                  <div>删除</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <tableOperateBtn v-else>
            <el-dropdown-item v-if="intelligentRowCanClick(scope.row)" @click.native="btnCheck(scope)">
              <div>查看</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="hasRouteAuth('crm:finance:edit') && !isIntelligent" :disabled="!(scope.row.verificationState === 0 && scope.row.sealingState === 0)" @click.native="btnEdit(scope)">
              <div>编辑</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="intelligentRowCanClick(scope.row)" @click.native="btnVerificate(scope)">
              <div>核销</div>
            </el-dropdown-item>
            <el-dropdown-item v-if="hasRouteAuth('crm:finance:delete') && !isIntelligent" :disabled="!(scope.row.verificationState === 0 && scope.row.sealingState === 0)" @click.native="btnDel(scope)">
              <div>删除</div>
            </el-dropdown-item>
          </tableOperateBtn>
        </template>
      </u-table-column>
    </u-table>
    <empty-placeholder v-else-if="!isInit" style="margin-bottom: 24px" />

    <el-dialog
      :visible.sync="dialogShow"
      :before-close="closeRemarkDialog"
      :append-to-body="true"
      class="order-setting-dialog small-common-dialog-size"
      width="450px">
      <div class="main">
        <Title :title="'编辑备注'" font-size="16px" style="margin-bottom:20px;"/>
        <el-form
          ref="configForm"
          :model="remarkParams"
          label-position="left"
          label-width="80px"
          class="setting-form">
          <el-form-item label="备注" prop="name" style="margin-bottom: 20px;">
            <el-input v-model.trim="remarkParams.remark" style="font-size: 14px;width:240px;" resize="none" rows="4" type="textarea" size="small" maxlength="500" placeholder="请输入备注，限制500个字"/>
          </el-form-item>
        </el-form>
        <div style="display:flex;justify-content:center;">
          <el-button type="primary" size="small" @click="handleOk">确定</el-button>
          <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="closeRemarkDialog()">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  setVerificationState,
  setPayWay,
  clientStatusFilter,
  setSealBillType
} from '@/filters/status';
import { standardFormat, standardFormatNoHour } from '@/filters/date';
import { moneyFilter } from '@/filters/number';
import { financeProps } from '@/components/OrderList/settingData';
import Title from '@/components/Title';
import { setRemark } from '@/api/finance';
import { hasRouteAuth } from '@/utils/permission';
// 跨页选中逻辑
import tableSelections from '@/mixins/tableSelections';
import mobileTable from '@/mixins/mobileTable';
// img
import setting from '@/assets/setting.png';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
export default {
  filters: {
    setVerificationState,
    setPayWay,
    standardFormat,
    standardFormatNoHour,
    moneyFilter,
    setSealBillType,
    flowType(val) {
      // 流水类型。0:普通 1:对抵
      let text = '--';
      switch (val) {
        case 0:
          text = '普通';
          break;
        case 1:
          text = '对抵';
          break;
      }
      return text;
    }
  },
  components: {
    EmptyPlaceholder, Title
  },
  mixins: [tableSelections, mobileTable],
  props: {
    listLoading: {
      type: Boolean,
      default: false
    },
    isInit: {
      type: Boolean,
      default: true
    },
    activeId: {
      type: Number | String,
      default: ''
    },
    financeListSetting: {
      type: Array,
      default: () => {
        return [];
      }
    },
    list: {
      type: Object | Array,
      default: () => {
        return {};
      }
    },
    tableHeight: {
      type: String,
      default: '100vh'
    },
    showOperate: {
      type: Boolean,
      default: true
    },
    openNewPage: {
      type: Boolean,
      default: false
    },
    isIntelligent: { // 是否是智能核销列表
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      financeProps,
      setting,
      sortType: '',
      sortName: '',
      dialogShow: false,
      remarkParams: {
        remark: '',
        id: '',
        item: null
      },
      tableRefName: 'dayAccountTableRef', // 表格的ref名称
      idKey: 'id', // 唯一表示字段
      isUmyTable: true
    };
  },
  watch: {
    activeId: {
      handler: function() {
        this.$nextTick(() => {
          if (this.clearMixinSelection) this.clearMixinSelection();
        });
      }
    },
    list: {
      handler: function(val, oldval) {
        this.$nextTick(() => {
          if (this.setSelectRow) this.setSelectRow(val.items);
        });
      },
      deep: true// 对象内部的属性监听，也叫深度监听
    }
  },
  methods: {
    hasRouteAuth,
    clientStatusFilter,
    intelligentRowCanClick(row) {
      return !this.isIntelligent || (this.isIntelligent && row.canOperate);
    },
    sortMethod(a) {
      if (a.order) {
        this.sortName = a.prop;
        this.sortType = a.order === 'ascending' ? 1 : -1;
      } else {
        this.sortName = '';
        this.sortType = '';
      }
      this.$emit('addSort', { sortName: this.sortName, sortType: this.sortType });
    },
    btnCheck(scope) {
      const routerData = {
        name: 'chargeOffDetail',
        params: { chargeOffId: scope.row.id }
      };
      if (this.isIntelligent) {
        routerData.query = { isIntelligent: 1 };
      }
      if (this.openNewPage) {
        const url = this.$router.resolve(routerData);
        window.open(url.href, '_blank');
      } else {
        this.$router.push(routerData);
      }
    },
    rowClick(row, column, event) {
      if (column.label !== '操作' && column.label !== '备注') {
        this.$router.push({
          name: 'chargeOffDetail',
          params: { chargeOffId: row.id }
        });
      }
    },
    toOrderDetail(row) {
      this.$emit('toOrderDetail', row);
    },
    tableSelectionChange(e) {
      this.$emit('handleSelectionChange', e);
    },
    btnVerificate(e) {
      this.$emit('btnVerificate', e);
    },
    btnEdit(scope) {
      this.$router.push({
        name: 'editDayAccount',
        params: { dayAccountId: scope.row.id }
      });
    },
    btnDel(scope) {
      this.$emit('btnDel', scope);
    },
    editRemark(item) {
      this.remarkParams = {
        remark: item.remark,
        id: item.id,
        item: item
      };
      this.dialogShow = true;
    },
    closeRemarkDialog() {
      this.dialogShow = false;
      this.remarkParams = {
        remark: '',
        id: '',
        item: null
      };
    },
    handleOk() {
      const params = {
        remark: this.remarkParams.remark,
        id: this.remarkParams.id
      };
      setRemark(params).then(res => {
        if (res.code === 200) {
          this.$message.success('设置成功');
          this.remarkParams.item.remark = params.remark;
          this.closeRemarkDialog();
        } else {
          this.$message.error(res.message);
        }
      }).catch(res => {
        console.log(res);
      });
    },
    getPayWay(row) {
      const clientType = this.clientStatusFilter(row.clientType);
      return row.payWayStr ? clientType + ' / ' + row.payWayStr : clientType;
    },
    clearSelection() {
      if (this.clearMixinSelection) this.clearMixinSelection();
    },
    toggleRowSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.dayAccountTableRef.toggleRowSelection([row]);
        });
      } else {
        this.$refs.dayAccountTableRef.clearSelection();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.el-dropdown-link {
  display: block;
  position: relative;
  padding-left:6px;
  margin-left: 6px;
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    margin-top: -7px;
    width: 1px;
    background: #ddd;
    height: 14px;
  }
}
.el-table {
  .pay-name, .pay-number {
    width: 141px;
  }
  .remark {
    max-width: 130px;
  }
}
.flex {
  display: flex;
  align-items: center;
}
.dot {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-right: 5px;
}
.dropdown-wrap {
  margin-top: -24px;
  margin-right: 15px;
  padding: 0;
  .el-dropdown-menu__item {
    width: 80px;
    text-align: center;
  }
}
.remarks-context {
  font-size: 14px;
  overflow:hidden;
  text-overflow:ellipsis;
  word-break:break-all;
  display:-webkit-box;
  -webkit-box-orient:vertical;
  line-clamp: 6;
  -webkit-line-clamp: 6;
}
</style>
